package com.mmall.concurrent.example.aqs;/**
 * Created with IDEA
 * Author : wangfei
 * Date :  2019/10/22
 * Time : 16:49
 * Describe :
 */

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @ClassName CountDownLatchExample1
 * @Describe :
 * @Author : wangfei
 * @Date :  2019/10/22 16:49
 */
@Slf4j
public class SemaphoreExample1 {

	private static int threadCount = 200;

	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(3);

		for (int i = 0; i < threadCount; i++) {
			final int threadNum = i;
			exec.execute(() ->{
				try {
					semaphore.acquire(); // 获取一个许可
					test(threadNum);
					semaphore.release(); // 释放一个许可
				} catch (InterruptedException e) {
					log.error("exception",e);
				}
			});
		}
		log.info("finish");
		exec.shutdown();
	}

	private static void test(int threadNum) throws InterruptedException {
		Thread.sleep(1000);
		log.info("task: {}", threadNum);
//		Thread.sleep(100);
	}

}
